<template>
  <a-card :bordered="false">
    <Header :title="'返回'" :subTitle="'添加新的成员'" :hasBackPath="true" @headerBack="$router.back()"></Header>
    <a-form-model
      ref="rulesForm"
      :model="form"
      :rules="rules"
      :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }"
      :wrapperCol="{ lg: { span: 19 }, sm: { span: 17 } }"
    >
      <a-form-model-item label="添加对象">
        <a-input
          style="width: 40%"
          v-model="mobile"
          placeholder="请填写手机号"
        />
        <a-button type="primary" style="margin-left: 15px;" @click="handleAddMember">确认添加</a-button>
        <a-upload
          accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          name="发券"
          :showUploadList="false"
          :multiple="false"
          :data="uploadData"
          :action="uploadUrl"
          @change="handleChange"
        >
          <a-button style="margin-left: 15px;">批量添加</a-button>
        </a-upload>
        <span style="margin-left: 15px;text-decoration: underline;color: blue;cursor: pointer" @click="handleExportSendUser">点击下载导入模版</span>
        <a-table style="margin-top: 20px;" bordered :pagination="pagination" :columns="memberColumns" :data-source="sendUserList"
                :rowKey="(record, index) => index" size="middle" @change="handleSendUserChange">
          <span slot="index" slot-scope="text, record, index">
            {{index+1}}
          </span>
          <span slot="jurisdiction" slot-scope="text, record, index">
            <a-radio-group v-model="record.jurisdiction">
              <a-radio :value="1">仅自己可见</a-radio>
              <a-radio :value="2">全部可见</a-radio>
            </a-radio-group>
          </span>
          <span slot="action" slot-scope="text, record, index">
            <a-popconfirm title="请确认是否删除本条信息？" @confirm="handleDeleteMember(record.mobile)">
              <a-icon type="delete" style="cursor: pointer;"/>
            </a-popconfirm>
          </span>
        </a-table>
      </a-form-model-item>
      <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button type="primary" :disabled="submitFlag" @click="handleSubmit">确认提交</a-button>
      </a-form-model-item>
    </a-form-model>
</a-card>
</template>
<script>
  import {
    sendUserList,
    addSendUser,
    deleteSendUser,
    sendUserExpert,
    sendUserBatchAdd
  } from '@/api/headquartersCoupon/index'
  import Header from '@/views/box/components/layouts/Header'
  const memberColumns = [
    {
      title: '序号',
      align: 'center',
      scopedSlots: { customRender: 'index' }
    },
    {
      title: '添加对象',
      align: 'center',
      dataIndex: 'mobile'
    },
    {
      title: '数据权限',
      align: 'center',
      scopedSlots: { customRender: 'jurisdiction' }
    },
    {
      title: '操作',
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    components: {
      Header
    },
    data() {
      return {
        submitFlag: false,
        form: {},
        rules: {
          departmentName: [
            { required: true, message: '请输入', trigger: 'blur' }
          ]
        },
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
        },
        memberColumns,
        sendUserList: [
          {
            id: 1,
            mobile: '15134567890',
            jurisdiction: 1
          },
          {
            id: 2,
            mobile: '15122222222',
            jurisdiction: 2
          }
        ],
        mobile: '',
        uploadData: {
          pageId: this.$route.params.id
        },
        exportUrl: sendUserExpert,
        uploadUrl: sendUserBatchAdd,
      }
    },
    computed: {},
    created() {
    },
    methods: {
      //下载导入模板
      handleExportSendUser() {
        window.location.href = this.exportUrl
      },
      // 批量添加发放对象
      handleChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          const { msg, message, code, result } = info.file.response
          if (code == 200) {
            this.refreshSendUserList()
            this.$message.success('共成功导入100条数据！')
            this.$confirm({
              title: '提示',
              content: '共成功导入90条数！据10条数据有误，点击下载相关数据',
              icon: 'none',
              closable: false,
              okText: '下载数据',
              onOk() {
                
              },
              onCancel() {
              }
            })
          } else {
            this.$message.error(msg || message)
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} file upload failed.`)
        }
      },
      // 单独添加发放对象
      handleAddMember() {
        const myreg = /^(1)\d{10}$/
        if (!this.mobile) {
          this.$message.info('未填写手机号！')
          return
        }
        if (!myreg.test(this.mobile)) {
          this.$message.info('手机号有误！')
          return
        }
        const data = {
          pageId: this.id,
          tel: this.mobile
        }
        addSendUser(data).then(res => {
          this.spinning = false
          if (res.code === 200) {
            this.mobile = ''
            this.refreshSendUserList()
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
          this.spinning = false
        })
      },

      // 删除发放对象
      handleDeleteMember(mobile) {
        const data = {
          pageId: this.id,
          tel: mobile
        }
        deleteSendUser(data).then(res => {
          this.spinning = false
          if (res.code === 200) {
            this.refreshSendUserList()
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
          this.spinning = false
        })
      },

      handleSendUserChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
        this.getSendUserList()
      },

      refreshSendUserList() {
        this.pagination.current = 1
        this.getSendUserList()
      },

      //发券对象列表
      getSendUserList() {
        const data = {
          pageId: this.id,
          current: this.pagination.current,
          size: this.pagination.pageSize
        }
        sendUserList(data).then(res => {
          if (res.code === 200) {
            const { officeSendUsers, totalUser, totalNoSub, totalNoCard } = res.data
            this.sendUserList = officeSendUsers.records
            const pagination = { ...this.pagination }
            pagination.total = officeSendUsers.total
            this.pagination = pagination
            this.totalNoCard = totalNoCard
            this.totalNoSub = totalNoSub
            this.totalUser = totalUser
            this.$emit('checkCard', this.checkCard(totalNoCard))
            this.$emit('checkFollow', this.checkFollow(totalNoSub))
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      //提交
      handleSubmit() {
        const that = this
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            if (!this.sendUserList.length) {
              this.$message.info('请先添加成员！')
              return
            }
            this.submitFlag = true
            const list = this.departments.filter(e => e.id == this.form.flow_id)
            const data = {
              id: this.id,
              ...this.form,
              flow_id: this.departmentId ? this.form.flow_id : '',
              department: list.length ? list[0].department : this.form.department,
              applyUse: this.usefor
            }
            submit(data).then(res => {
              if (res.code === 200) {
                // this.submitFlag = false
                if (this.sendType == 1) {
                  this.$info({
                    title: '提交成功！消息已发送～',
                    icon: 'none',
                    okText: '返回',
                    closable: false,
                    onOk() {
                      that.$router.go(-1)
                    }
                  })
                } else {
                  this.$router.go(-1)
                }
              } else {
                this.submitFlag = false
                this.$message.error(res.msg || res.message)
              }
            })

          } else {
            return false
          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>
</style>
